package cn.adolf.carmaster.ui;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import cn.adolf.carmaster.CommandActivity;
import cn.adolf.carmaster.R;
import cn.adolf.carmaster.helper.ToastUtil;
import cn.adolf.carmaster.databinding.FragmentOperationBinding;


public class OperationFragment extends Fragment {
    private static final String TAG = "OperationFragment";
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private FragmentOperationBinding binding;
    private String mSuPath;
    private String mApkAbsName;

    public OperationFragment() {
    }

    public static OperationFragment newInstance() {
        OperationFragment fragment = new OperationFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentOperationBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.btnSdApk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doCommend("ls /sdcard/*.apk");
            }
        });

        binding.btnUsbApk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doCommend("ls /storage/usbotg/usbotg-sda1/*.apk");
            }
        });

        binding.btnScreenCap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doCmdByDelay("mkdir /sdcard/_aaa", 300);
                doCmdByDelay("screencap -p /sdcard/_aaa/" + System.currentTimeMillis() + ".jpg", 500);
            }
        });

        binding.etCmdInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                Log.d(TAG, "onKey: actionId=" + actionId);
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    String cmd = binding.etCmdInput.getText().toString();
                    if (!TextUtils.isEmpty(cmd) && mCmdListener != null) {
                        mCmdListener.onCmd(cmd);
                        binding.etCmdInput.setText("");
                    }
                }
                return true;
            }
        });

        binding.btnSendCmd.setOnClickListener(v -> {
            String cmd = binding.etCmdInput.getText().toString();
            if (!TextUtils.isEmpty(cmd) && mCmdListener != null) {
                mCmdListener.onCmd(cmd);
                binding.etCmdInput.setText("");
            }
        });

        binding.btnDoSu.setOnClickListener(v -> {
            // mSuPath = binding.etSuPath.getText().toString();
            // if (TextUtils.isEmpty(mSuPath)) {
            //     ToastUtil.show("请填写mtk-su路径");
            //     return;
            // }
            // if (mSuPath.charAt(0) != '/') {
            //     mSuPath = "/" + mSuPath;
            // }
            InfoDialog infoDialog = new InfoDialog("获取临时root", getResources().getString(R.string.getRoot), isConfirm -> {
                if (isConfirm) {
                    new Thread(() -> {
                        doCmdByDelay("cd " + "/data/local/tmp/", 300);
                        // SystemClock.sleep(1500);
                        doCmdByDelay("./mtk-su", 3000);
                        // SystemClock.sleep(1500);
                        doCmdByDelay("mount -r -w -o remount -t ext4 /system", 1500);
                        // SystemClock.sleep(1500);
                        ToastUtil.show("执行结束", 5000);
                    }).start();
                }
            });
            infoDialog.show(getActivity().getSupportFragmentManager(), "info");
        });

        binding.btnDoUsbInstall.setOnClickListener(v -> {
            mApkAbsName = binding.etApkName.getText().toString();
            String tempName = "";
            if (!mApkAbsName.startsWith("/")) {
                tempName = "u盘/" + mApkAbsName;
                mApkAbsName = "/storage/usbotg/usbotg-sda1/" + mApkAbsName;
            } else {
                ToastUtil.show("开头请不要带'/'字符");
                return;
            }

            String name = mApkAbsName.substring(mApkAbsName.lastIndexOf("/") + 1);
            if (TextUtils.isEmpty(mApkAbsName) || TextUtils.isEmpty(name) || ".apk".equals(name)) {
                ToastUtil.show("请输入U盘目录下的apk名称（包括后缀）");
                return;
            }


            InfoDialog infoDialog = new InfoDialog("安装：" + tempName, getResources().getString(R.string.install) + "是否安装："+tempName, isConfirm -> {
                if (isConfirm) {
                    new Thread(() -> {
                        doCmdByDelay("cp " + mApkAbsName + " /data/app", 200);
                        // SystemClock.sleep(2000);
                        // doCmdByDelay("cd /data/app", 2500);
                        // SystemClock.sleep(1500);
                        doCmdByDelay("chmod 777 " + "/data/app/" + name, 2500);
                        // SystemClock.sleep(1500);
                        ToastUtil.show("执行结束", 3000);
                    }).start();
                }

            });
            infoDialog.show(getActivity().getSupportFragmentManager(), "info");

        });


        binding.btnDoInstall.setOnClickListener(v -> {
            String tempName = "";
            mApkAbsName = binding.etApkName.getText().toString();
            if (!mApkAbsName.startsWith("/")) {
                tempName = "sdcard/" + mApkAbsName;
                mApkAbsName = "/sdcard/" + mApkAbsName;
            } else {
                ToastUtil.show("开头请不要带'/'字符");
                return;
            }

            String name = mApkAbsName.substring(mApkAbsName.lastIndexOf("/") + 1);
            if (TextUtils.isEmpty(mApkAbsName) || TextUtils.isEmpty(name) || ".apk".equals(name)) {
                ToastUtil.show("请输入sdcard目录下的apk名称（包括后缀）");
                return;
            }

            InfoDialog infoDialog = new InfoDialog("安装：" + tempName, getResources().getString(R.string.install) +  "是否安装："+tempName, isConfirm -> {
                if (isConfirm) {
                    new Thread(() -> {
                        doCmdByDelay("cp " + mApkAbsName + " /data/app", 200);
                        // SystemClock.sleep(2000);
                        // doCmdByDelay("cd /data/app", 2500);
                        // SystemClock.sleep(1500);
                        doCmdByDelay("chmod 777 " + "/data/app/" + name, 2500);
                        // SystemClock.sleep(1500);
                        ToastUtil.show("执行结束", 3000);
                    }).start();

                }

            });
            infoDialog.show(getActivity().getSupportFragmentManager(), "info");


        });

        binding.btnCpMtkSu.setOnClickListener(v -> {
            InfoDialog infoDialog = new InfoDialog("拷贝mtk-su", getResources().getString(R.string.moveMTKSU), isConfirm -> {
                if (isConfirm) {
                    new Thread(() -> {
                        doCmdByDelay("cp /sdcard/mtk-su /data/local/tmp/", 200);
                        // SystemClock.sleep(2000);
                        // doCmdByDelay("cd /data/local/tmp");
                        // SystemClock.sleep(1500);
                        doCmdByDelay("chmod 755 /data/local/tmp/mtk-su", 2000);
                        // SystemClock.sleep(1500);
                        ToastUtil.show("执行结束", 3000);
                    }).start();
                }

            });
            infoDialog.show(getActivity().getSupportFragmentManager(), "info");

        });

        // binding.etApkName.addTextChangedListener(new TextWatcher() {
        //     @Override
        //     public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        //     }
        //
        //     @Override
        //     public void onTextChanged(CharSequence s, int start, int before, int count) {
        //         binding.tvContentInstall.setText(String.format("安装： %s", s));
        //     }
        //
        //     @Override
        //     public void afterTextChanged(Editable s) {
        //     }
        // });

        binding.etSuPath.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                binding.tvContentSu.setText(String.format("申请临时root： %s", s));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    public void doCommend(String cmd) {
        if (mCmdListener != null) {
            mCmdListener.onCmd(cmd);
        }
    }

    public void doCmdByDelay(String cmd, long delay) {
        binding.btnSendCmd.postDelayed(() -> {
            if (mCmdListener != null) {
                mCmdListener.onCmd(cmd);
            }
        }, delay);
    }



    private CommandActivity.OnCmdListener mCmdListener;

    public void setCmdListener(CommandActivity.OnCmdListener cmdListener) {
        mCmdListener = cmdListener;
    }
}